import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../models/device/device.dart';
import '../../providers/device_providers.dart';
import '../../providers/multi_video_player_provider.dart';
import '../../widgets/player/function_button_bar.dart';
import '../../widgets/video_window_layout.dart';

class MultiPlayerPage extends ConsumerStatefulWidget {
  final Device device;

  const MultiPlayerPage({super.key, required this.device});

  @override
  ConsumerState<MultiPlayerPage> createState() => _MultiPlayerPageState();
}

class _MultiPlayerPageState extends ConsumerState<MultiPlayerPage> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final notifier = ref.read(multiVideoPlayerProvider.notifier);
      notifier.changedDevice(widget.device.id!);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _PlayPageAppBar(device: widget.device),
      // backgroundColor: Colors.black,
      body: bodyWidget(),
    );
  }

  Widget bodyWidget() {
    //TODO: 横屏
    return Column(
      children: [
        playerContainer(),
        Expanded(
          child: controlPanel(),
        ),
      ],
    );
  }

  Widget playerContainer() {
    //TODO: 实现双摄悬浮，上下分屏
    return AspectRatio(
      aspectRatio: 4.0 / 3.0,
      child: VideoWindowLayout(
        onRefresh: (p0) {},
        onVideoTap: (p0) {},
      ),
    );
  }

  Widget controlPanel() {
    return FunctionButtonBar(
      onCapture: () {},
      onRecord: () {},
      onTalk: () {},
      onWarning: () {},
      onTogglePTZ: () {},
      isPlaying: false,
    );
  }
}

class _PlayPageAppBar extends ConsumerWidget implements PreferredSizeWidget {
  final Device device;

  const _PlayPageAppBar({required this.device});

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final multiState = ref.watch(multiVideoPlayerProvider);

    final device = ref.read(deviceListProvider).value?.firstWhere((e) =>
            e.id == (multiState.value?.currentDeviceId ?? this.device.id)) ??
        this.device;

    return AppBar(
      title: Text(
        device.name ?? '视频监控',
        style: const TextStyle(color: Colors.white),
      ),
      centerTitle: true,
    );
  }
}
